//
//  CLNetworkManager4JSON.m
//  CareLinkApp_iOS19
//
//  Created by 刘家强 on 16/8/21.
//  Copyright © 2016年 Seven Team. All rights reserved.
//

#import "CLNetworkManager4JSON.h"

@interface CLNetworkManager4JSON ()

@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;

@end

@implementation CLNetworkManager4JSON

#pragma mark - 但例
+ (instancetype)sharedManager {
    // 静态区
    static CLNetworkManager4JSON *instance;
    
    // 令牌
    static dispatch_once_t onceToken;
    
    // 仅执行一次
    dispatch_once(&onceToken, ^{
        instance = [self new];
    });
    return instance;
}

#pragma mark - 懒加载
- (AFHTTPSessionManager *)sessionManager {
    // 如果为空 初始化
    if (_sessionManager == nil) {
        _sessionManager = [AFHTTPSessionManager manager];
        
        // 设置请求和相应的 解析器
        _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
//        _sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        // 添加解析集合
        NSSet *set = [NSSet setWithObjects:@"text/plain", @"text/html", nil];
        
        _sessionManager.responseSerializer.acceptableContentTypes = [_sessionManager.responseSerializer.acceptableContentTypes setByAddingObjectsFromSet:set];
    }
    return _sessionManager;
}

- (void)POST:(NSString *)urlString parameters:(NSDictionary *)paramDic success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
    [self.sessionManager POST:urlString parameters:paramDic progress:nil success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        success(responseObject);
    }
                      failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
                          NSLog(@"网络请求错误 %@", error);
                          failure(error);
                      }];
}

- (void)POST:(NSString *)urlString parameters:(NSDictionary *)paramDic success:(void (^)(NSDictionary *jsonData, NSString *msg))success {
    [self.sessionManager POST:urlString parameters:paramDic progress:nil success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        success([responseObject objectForKey:@"data"], [responseObject objectForKey:@"msg"]);
    }
                      failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
                          NSLog(@"网络请求错误 %@", error);
                      }];
}

@end

